﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RzCorportativo.Lib;
using System.IO;

namespace  RzCorportativo
{
    public class BasePage : System.Web.UI.Page
    {
        public static Login CurrentLogin { get { return AppSession.Login; } }

        public static bool IsAuthenticate { get { return CurrentLogin != null; } }

        protected override void OnInit(EventArgs e)
        {
            bool @result = false;
            if (!BasePage.IsAuthenticate || BasePage.CurrentLogin == null)
            {
                string accessDenied = System.Web.Configuration.WebConfigurationManager.AppSettings["_urlAccessDenied"];
                this.Response.Redirect(ResolveUrl("~/"));
                return;
            }
            else if (!this.Request.Url.AbsoluteUri.EndsWith("Cadastros/Usuario.aspx?op=nc") && !BasePage.CurrentLogin.CadastroCompleto)
            {
                this.Response.Redirect(this.ResolveUrl("~/Default.aspx"));
                return;
            }
            var type = this.GetType().BaseType;
            var attr = type.GetCustomAttributes(typeof(Lib.PermissaoAttribute), false).FirstOrDefault() as Lib.PermissaoAttribute;
            if (attr != null && attr.HasValidation && !attr.GetPermission(BasePage.CurrentLogin, new ItemSistema() { Nome = type.Name }))
            {
                this.Response.Redirect(this.ResolveUrl("~/Default.aspx?op=ad")); // ad = access denied
                return;
            }
            base.OnInit(e);
        }

        internal static void Autenticar(Login eLogin)
        {
            AppSession.Login = eLogin;
            if(eLogin == null)
                return;
            //var itens = Medico.Listar(new Medico() { PessoaId = eLogin.UsuarioId});
            //var item = itens.FirstOrDefault();
            //if(item == null)
            //    return;
            //AppSession.Medico = item;
        }
        protected string ObterFoto()
        {
            string file = ResolveUrl("~/Recursos/upload/") + (Request.QueryString["usuarioId"] ?? "") + ".jpg";
            return File.Exists(Server.MapPath(file)) ? file : ResolveUrl("~/Recursos/upload/") + "avatar.jpg";
        }
        internal static void Sair()
        {
            HttpContext.Current.Session.RemoveAll();
        }
    }
}